package com.btcode.netty.server.session.util;

import com.btcode.redis.RedisDbExecute;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StationService {
    private static StationService _instance;
    private final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private StationService() {
    }

    public static StationService getInstance() {
        if (_instance == null) {
            _instance = new StationService();
        }
        return _instance;
    }

    /**
     * 设置站房系统运行状态
     * gislin
     * 2016年7月2日
     *
     * @param mn
     * @param statusName
     * @param value
     */
    public void setSysStatus(String mn, String statusName, String value) {
        RedisDbExecute.setString("stationInfo:" + mn + ":sysStatus:" + statusName, value);
    }

    /**
     * 设置质控配置信息
     * gislin
     * 2016年7月2日
     *
     * @param mn
     * @param configName
     * @param value
     */
    public void setQualityConfig(String mn, String configName, String value) {
        RedisDbExecute.setString("stationInfo:" + mn + ":qualityConfig:" + configName, value);
    }
    /**
     * 检查天的请求编号是否已经处理，防止重复处理
     * gislin
     * 2016年7月2日
     *
     * @param mn
     * @param qn
     * @return
     */
//    public boolean isDayQNReceive(DataType dataType, String mn, String qn) {
//
//        String type = "";
//
//        if (dataType == DataType.day) {
//            type = "Day";
//        } else if (dataType == DataType.hour) {
//            type = "Hour";
//        } else if (dataType == DataType.configSoftHourData) {
//            type = "configSoftHour";
//        } else if (dataType == DataType.configSoftDayData) {
//            type = "configSoftDay";
//        }
//
//        String value = RedisDbExecute.getString(type + ":" + qn + ":" + mn);
//        if ("1".equals(value)) {
//            return true;
//        } else {
//            return false;
//        }
//    }
    /**
     * 设置天的请求编号已处理
     * gislin
     * 2016年7月2日
     *
     * @param mn
     * @param qn
     */
//    public void setDayQNReceived(DataType dataType, String mn, String qn) {
//        String type = "";
//
//        if (dataType == DataType.day) {
//            type = "Day";
//        } else if (dataType == DataType.hour) {
//            type = "Hour";
//        } else if (dataType == DataType.configSoftHourData) {
//            type = "configSoftHour";
//        } else if (dataType == DataType.configSoftDayData) {
//            type = "configSoftDay";
//        }
//        RedisDbExecute.setString(type + ":" + qn + ":" + mn, "1", 300);
//    }

    /**
     * 获取设备的某个信息
     * gislin
     * 2016年7月2日
     *
     * @param mn
     * @param deviceInfoKey
     * @return
     */
    public String getDeviceInfoValue(String mn, String deviceInfoKey) {
        return RedisDbExecute.getString("stationInfo:" + mn + ":deviceInfo:" + deviceInfoKey);
    }

    /**
     * 设置设备的某个信息
     * gislin
     * 2016年7月2日
     *
     * @param mn
     * @param deviceInfoKey
     * @param value
     */
    public void setDeviceInfoValue(String mn, String deviceInfoKey, String value) {
        RedisDbExecute.setString("stationInfo:" + mn + ":deviceInfo:" + deviceInfoKey, value);
    }

    /**
     * 设置站点状态
     * gislin
     * 2016年7月2日
     *
     * @param status
     * @param mn
     */
    public void setStationStatus(StationStatus status, String mn) {
        executor.execute(() -> RedisDbExecute.setString("stationInfo:" + mn + ":stationStatus", status.getCode()));
    }

    /**
     * 把所有点的状态重置为下线
     * gislin
     * 2016年7月5日
     */
    public void setAllStationOffline() {
        Set<String> keys = RedisDbExecute.queryKeys("stationInfo:*:stationStatus");
        for (String key : keys) {
            RedisDbExecute.setString(key, StationStatus.fault.getCode());
        }
    }

    /**
     * 更新站点数据接收时间，用于判断是否在线是否活动用
     * gislin
     * 2016年7月2日
     *
     * @param mn
     */
    public void updateStationDataReceiveTime(String mn) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RedisDbExecute.setString("stationInfo:" + mn + ":deviceInfo:DataTime_s", sf.format(new Date()));
    }

    /**
     * 更新站点最后的数据时间
     * gislin
     * 2016年7月2日
     *
     * @param mn
     */
    public void updateStationDataTime(String mn, Date dataTime) {
        if (dataTime != null) {
            RedisDbExecute.setString("stationInfo:" + mn + ":deviceInfo:DataTime", new SimpleDateFormat("yyyyMMddHHmmss").format(dataTime));
        }
    }

    /**
     * 获取污染物的报警下限阀值
     * gislin
     * 2016年5月13日
     *
     * @return
     * @throws Exception
     */
    public Double getPollAlarmDown(String mn, String pollCode) throws Exception {
        String hasKey = RedisDbExecute.getString("sysDict:stationPollAlarm:hasKey");
        if (hasKey == null || hasKey.trim().equals("")) {
            initStationPollAlarm();
        }
        Double down;
        try {
            down = RedisDbExecute.getDouble("sysDict:stationPollAlarm:" + mn + ":" + pollCode + ":down");
        }
        catch (Exception e) {
            return null;
        }
//		if(down == null){
//			down = RedisDbExecute.getDouble("sysDict:stationPollAlarm:default:"+pollCode+":down");
//		}
        return down;
    }

    /**
     * 获取污染物的报警上限阀值
     * gislin
     * 2016年5月13日
     *
     * @return
     * @throws Exception
     */
    public Double getPollAlarmUp(String mn, String pollCode) throws Exception {
        String hasKey = RedisDbExecute.getString("sysDict:stationPollAlarm:hasKey");
        if (hasKey == null || hasKey.trim().equals("")) {
            initStationPollAlarm();
        }
        Double up;
        try {
            up = RedisDbExecute.getDouble("sysDict:stationPollAlarm:" + mn + ":" + pollCode + ":up");
        }
        catch (Exception e) {
            return null;
        }
//		if(up == null){
//			up = RedisDbExecute.getDouble("sysDict:stationPollAlarm:default:"+pollCode+":up");
//		}
        return up;
    }

    /**
     * 初始化站点污染物报警阀值信息
     * gislin
     * 2016年5月13日
     *
     * @throws Exception
     */
    @SuppressWarnings({"RedundantThrows", "UnusedDeclaration"})
    void initStationPollAlarm() throws Exception {
//		String sql = "select sp.name pollcode,"
//				+"	t.density_alarm_dowmlimit down,"
//			    +"   t.density_alarm_uplimit up,"
//				+ "dc.device_num mn,"
//				+ "ABNORMAL_ALARM_DOWN,"
//				+ "ABNORMAL_ALARM_UP "
//				+ "from site_pollutants sp\n" +
//						"       left join monitor_station ms on sp.site_id = ms.code\n" + 
//						"       left join data_collection_instrumet dc on dc.site_id = ms.code"+
//						"  left join poll_alarm_threshold_set t on t.mn = dc.device_num and t.mn = dc.device_num and t.pollute_code = sp.name and t.is_standard = '1'";
//
//		DataTable table = DbManager.getOracleExecuter().executeQuery(sql, null);
//		
//		for(int i=0;i<table.getRecordCount();i++){
//			String pollCode = table.getString(i, "POLLCODE");
//			String down = table.getString(i, "DOWN");
//			String up = table.getString(i, "UP");
//			String mn = table.getString(i, "MN");
//			String abnormalDown = table.getString(i,"ABNORMAL_ALARM_DOWN");
//			String abnormalUp = table.getString(i,"ABNORMAL_ALARM_UP");
//			String stationCategory = table.getString(i,"station_category");
//			
//			RedisDbExecute.setString("sysDict:stationPollAlarm:"+mn+":"+pollCode+":down",down);
//			RedisDbExecute.setString("sysDict:stationPollAlarm:"+mn+":"+pollCode+":up",up);
//			RedisDbExecute.setString("sysDict:stationPollAlarm:"+mn+":"+pollCode+":abnormal_down",abnormalDown);
//			RedisDbExecute.setString("sysDict:stationPollAlarm:"+mn+":"+pollCode+":abnormal_up",abnormalUp);
//			RedisDbExecute.setString("sysDict:stationPollAlarm:"+mn+":station_category",stationCategory);
//		}
//		
//		RedisDbExecute.setString("sysDict:stationPollAlarm:hasKey","1");
    }

    /**
     * 获取污染物的异常下限阀值
     * wencheng
     * 2016年8月16日
     *
     * @return
     * @throws Exception
     */
    public Double getPollAbnormalDown(String mn, String pollCode) throws Exception {
        String hasKey = RedisDbExecute.getString("sysDict:stationPollAlarm:hasKey");
        if (hasKey == null || hasKey.trim().equals("")) {
            initStationPollAlarm();
        }
        Double down;
        try {
            down = RedisDbExecute.getDouble("sysDict:stationPollAlarm:" + mn + ":" + pollCode + ":abnormal_down");
        }
        catch (Exception e) {
            return null;
        }
        return down;
    }

    /**
     * 获取污染物的报警上限阀值
     * wencheng
     * 2016年8月16日
     *
     * @return
     * @throws Exception
     */
    public Double getPollAbnormalUp(String mn, String pollCode) throws Exception {
        String hasKey = RedisDbExecute.getString("sysDict:stationPollAlarm:hasKey");
        if (hasKey == null || hasKey.trim().equals("")) {
            initStationPollAlarm();
        }
        Double up;
        try {
            up = RedisDbExecute.getDouble("sysDict:stationPollAlarm:" + mn + ":" + pollCode + ":abnormal_up");
        }
        catch (Exception e) {
            return null;
        }
        return up;
    }

    /**
     * 初始化MEAS_NORMAL
     * 张文成
     * 2016年11月09日
     *
     * @throws Exception
     */
    @SuppressWarnings({"RedundantThrows", "EmptyCatchBlock", "ConstantConditions", "UnusedDeclaration"})
    public void initStationMEAS_NORMAL() throws Exception {
        Pattern p = Pattern.compile("stationInfo:(.*):deviceInfo:(.*)_MEAS");//用于提取mn号
        String findKey = "stationInfo:*:deviceInfo:*_MEAS";
        Set<String> keys = RedisDbExecute.queryKeys(findKey);
        Matcher m;
        for (String key : keys) {
            if (!key.endsWith("MEAS")) {
                continue;
            }
            m = p.matcher(key);
            try {
                if (m.find()) {
                    String mn = m.group(1);
                    String pollCode = m.group(2);
                    if (key != null && !key.isEmpty() && key.length() > 10) {
                        Double value = RedisDbExecute.getDouble(key);
                        if (value < 0) {
                            if ("001".equals(pollCode)) {
                                value = 6.7;
                            }
                            if ("011".equals(pollCode)) {
                                value = 15.6;
                            }
                            if ("060".equals(pollCode)) {
                                value = 11.5;
                            }
                            if ("101".equals(pollCode)) {
                                value = 1.16;
                            }
                            if ("ss".equals(pollCode)) {
                                value = 216.6;
                            }
                            if ("phtem".equals(pollCode)) {
                                value = 25.6;
                            }
                            if ("B01".equals(pollCode)) {
                                value = 0.0;
                            }
                            if ("B01TOTAL".equals(pollCode)) {
                                value = 0.0;
                            }
                            StationService.getInstance().setDeviceInfoValue(mn, pollCode + "_MEAS_NORMAL", value.toString());
                        }
                        else {
                            StationService.getInstance().setDeviceInfoValue(mn, pollCode + "_MEAS_NORMAL", value.toString());
                        }
                    }
                }
            }
            catch (Exception e) {
            }
        }
    }

    /**
     * 初始化MEAS_NORMAL
     * 张文成
     * 2016年11月09日
     *
     * @throws Exception
     */
    @SuppressWarnings({"RedundantThrows", "EmptyCatchBlock", "ConstantConditions", "UnusedDeclaration"})
    public void delete_NORMAL() throws Exception {
        Pattern p = Pattern.compile("stationInfo:(.*):deviceInfo:(.*)_MEAS_NORMAL");//用于提取mn号
        String findKey = "stationInfo:*:deviceInfo:*_NORMAL";
        Set<String> keys = RedisDbExecute.queryKeys(findKey);
        Matcher m;
        for (String key : keys) {
            m = p.matcher(key);
            try {
                if (m.find()) {
                    String mn = m.group(1);
                    String pollCode = m.group(2);
                    if (key != null && !key.isEmpty() && key.length() > 10) {
                        RedisDbExecute.deleteKeys("stationInfo:" + mn + ":deviceInfo:" + pollCode + "_NORMAL");
                    }
                }
            }
            catch (Exception e) {
            }
        }
    }

    /**
     * 设置开关量（是否可以设置正常状态）   0:无设备故障  1:设备故障
     * 张文成
     * 2016年12月9日
     *
     * @param status
     * @param mn
     */
    public void setStationDeviceFault(String status, String mn) {
        RedisDbExecute.setString("stationInfo:" + mn + ":stationDeviceFault", status);
    }

    /**
     * 获取开关量（是否可以设置正常状态）   0:无设备故障  1:设备故障
     * 张文成
     * 2016年12月9日
     *
     * @param mn
     */
    public String getStationDeviceFault(String mn) {
        String value = RedisDbExecute.getString("stationInfo:" + mn + ":stationDeviceFault");
        if (value == null) {
            value = "0";
        }
        return value;
    }

    public void addMN2StationBlacklist(String mn) {
        RedisDbExecute.setString("sysDict:stationBlacklist:" + mn, "true");
    }

    public void deleteMNFromStationBlacklist(String mn) {
        RedisDbExecute.deleteKeys("sysDict:stationBlacklist:" + mn);
    }

    public boolean checkMNFromStationBlacklist(String mn) {
        String exist = RedisDbExecute.getString("sysDict:stationBlacklist:" + mn);
        return exist != null && exist.equals("true");
    }
}
